package pers.vinsonws.jianghu.clientwin;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import pers.vinsonws.jianghu.clientwin.handler.ChatClientHandler;
import pers.vinsonws.jianghu.codeCompont.MsgEveryPro;

/**
 * @auther vinsonws
 * @date 2018/11/4 20:38
 */
public class JianghuClientNetStart {
    public void run() {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new ProtobufVarint32FrameDecoder())
                                .addLast(new ProtobufDecoder(MsgEveryPro.Message.getDefaultInstance()))
                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(new ChatClientHandler());
                    }
                });
        try {
            bootstrap.connect("127.0.0.1", 25347).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("connect fail");
            System.exit(1);
        }
    }
}
